package com.photo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.photo.util.CameraUtil;
import com.photo.util.ImageUtil;
import com.photo.util.KeyImage;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private final String TAG = MainActivity.class.getSimpleName();
    ImageView imageView;
    /**
     * 充当标题栏布局
     */
    View mTitle;
    private final int PHOTO_ALBUM = 2;// 从相册中选择

    private final int PHOTO_CROP_RESULT = 3;// 结果
    // 用于拍照上传
    private final int PHOTO_CAMERA = KeyImage.xiang_ji;
    Uri photoUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.photo);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permis();
            }
        });
    }

    private void permis() {
        PermissionUtils utils = new PermissionUtils();
        utils.checkPermission(this, new PermissionUtils.PerListener() {
                    @Override
                    public void onPermissionSuccess() {
//                        callCamera();

                        CameraUtil cameraUtil = new CameraUtil();
                        cameraUtil.goCamera(MainActivity.this);
                    }

                    @Override
                    public void onPermissionFail() {

                    }
                }, Manifest.permission.CAMERA
                , Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    private void callCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File outDir = new File(getAppRootPath());
        if (!outDir.exists()) {
            outDir.mkdirs();
        }
        File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
        photoUri = Uri.fromFile(outFile);
        intent.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, PHOTO_CAMERA);
    }

    private String getAppRootPath() {
        String filePath = "";
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            filePath = Environment.getExternalStorageDirectory() + "/"
                    + Environment.DIRECTORY_PICTURES;
        } else {
            filePath = getApplication().getCacheDir() + "/"
                    + Environment.DIRECTORY_PICTURES;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return filePath;
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @function:
     * @author:Jerry
     * @date:2013-12-30
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_CROP_RESULT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PHOTO_ALBUM:
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    // upLoadPhoto(uri);
                    // initPicture(uri);
                    crop(uri);
                }
                break;
            case PHOTO_CAMERA:
                Uri uri = null;
                if (data != null && data.getData() != null) {
                    uri = data.getData();
                }

                // 一些机型无法从getData中获取uri，则需手动指定拍照后存储照片的Uri
                if (uri == null) {
                    if (photoUri != null) {
                        uri = photoUri;
                    }
                }
                LogUtil.i(true, TAG, "UserInfoAct: onActivityResult: [requestCode, resultCode, data]="
                        + uri.getPath());
//                toast(uri.getPath());
                // initPicture(uri);
                ImageUtil imageUtil = new ImageUtil();
                String path = imageUtil.getRealFilePath(this, uri);
                int degree = imageUtil.readPictureDegree(path);
                if (degree != 0) {
                    Bitmap getimage = imageUtil.getImageLoad(path);
                    if (getimage != null) {// 处理拍的照片翻转问题
                        Bitmap bitmap2 = imageUtil.rotaingImageView(degree,
                                getimage);
                        uri = Uri
                                .parse(MediaStore.Images.Media.insertImage(
                                        this.getContentResolver(), bitmap2,
                                        null, null));
                    }
                }
                startPhotoZoom(uri);
                break;
            case PHOTO_CROP_RESULT:
                if (data != null) {
                    try {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
//                            upLoadPhoto(extras);
                            Bitmap bitmap = extras.getParcelable("data");
//                            mPhoto.setImageBitmap(bitmap);
                            imageView.setImageBitmap(bitmap);
                        } else {
                            toast("fail_to_getphoto");
                        }

                        // FileInputStream in=new file
                        //
                        // boolean delete = tempFile.delete();
                        // System.out.println("delete = " + delete);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
         * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CROP_RESULT);
    }

    public void toast(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }
}
